#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "hi_wifi_api.h"
#include "lwip/ip_addr.h"
#include "lwip/netifapi.h"
#include "lwip/sockets.h"
#include "mqtt_test.h"

#define APP_INIT_VAP_NUM    2
#define APP_INIT_USR_NUM    2
#define SSID_NUM            32

int wifi_ok_flg = 0;  // WiFi连接成功标志
static struct netif *g_lwip_netif = NULL;

// 重置网卡IP、网关、子网掩码
void hi_sta_reset_addr(struct netif *pst_lwip_netif)
{
    ip4_addr_t st_gw;
    ip4_addr_t st_ipaddr;
    ip4_addr_t st_netmask;

    if (pst_lwip_netif == NULL) {
        printf("hisi_reset_addr::Null param of netdev\r\n");
        return;
    }

    IP4_ADDR(&st_gw, 0, 0, 0, 0);
    IP4_ADDR(&st_ipaddr, 0, 0, 0, 0);
    IP4_ADDR(&st_netmask, 0, 0, 0, 0);

    netifapi_netif_set_addr(pst_lwip_netif, &st_ipaddr, &st_netmask, &st_gw);
}

// WiFi事件回调函数（连接/断开/扫描完成等）
void wifi_wpa_event_cb(const hi_wifi_event *hisi_event)
{
    if (hisi_event == NULL)
        return;

    switch (hisi_event->event) {
        case HI_WIFI_EVT_SCAN_DONE:
            printf("WiFi: Scan results available\r\n");
            break;
        case HI_WIFI_EVT_CONNECTED:
            printf("WiFi: Connected\r\n");
            netifapi_dhcp_start(g_lwip_netif);  // 启动DHCP获取IP
            wifi_ok_flg = 1;                    // 更新连接标志
            break;
        case HI_WIFI_EVT_DISCONNECTED:
            printf("WiFi: Disconnected\r\n");
            netifapi_dhcp_stop(g_lwip_netif);   // 停止DHCP
            hi_sta_reset_addr(g_lwip_netif);    // 重置网卡地址
            break;
        case HI_WIFI_EVT_WPS_TIMEOUT:
            printf("WiFi: wps is timeout\r\n");
            break;
        default:
            break;
    }
}

// 连接指定WiFi热点
int hi_wifi_start_connect(void)
{
    int ret;
    errno_t rc;
    hi_wifi_assoc_request assoc_req = {0};

    // 修改为你的WiFi热点名称和密码
    char ssid_name[SSID_NUM] = "team12";  // 替换为实际WiFi名称
    char ssid_passwd[SSID_NUM] = "zch123456"; // 替换为实际WiFi密码
    int name_len = strlen(ssid_name);
    int passwd_len = strlen(ssid_passwd);

    // 拷贝WiFi名称到连接请求结构体
    rc = memcpy_s(assoc_req.ssid, HI_WIFI_MAX_SSID_LEN + 1, ssid_name, name_len);
    if (rc != EOK) {
        return -1;
    }

    assoc_req.auth = HI_WIFI_SECURITY_WPA2PSK;  // WiFi加密方式（WPA2-PSK）
    memcpy(assoc_req.key, ssid_passwd, passwd_len);  // 拷贝WiFi密码

    // 连接WiFi
    ret = hi_wifi_sta_connect(&assoc_req);
    if (ret != HISI_OK) {
        printf("WiFi connect failed, ret=%d\r\n", ret);
        return -1;
    }

    return 0;
}

// 初始化WiFi STA模式（客户端模式）
int hi_wifi_start_sta(void)
{
    int ret;
    char ifname[WIFI_IFNAME_MAX_SIZE + 1] = {0};
    int len = sizeof(ifname);
    const unsigned char wifi_vap_res_num = APP_INIT_VAP_NUM;
    const unsigned char wifi_user_res_num = APP_INIT_USR_NUM;
    unsigned int num = WIFI_SCAN_AP_LIMIT;

    // 启动WiFi STA模式，获取网卡名称
    ret = hi_wifi_sta_start(ifname, &len);
    if (ret != HISI_OK) {
        printf("hi_wifi_sta_start failed, ret=%d\r\n", ret);
        return -1;
    }

    // 注册WiFi事件回调函数
    ret = hi_wifi_register_event_callback(wifi_wpa_event_cb);
    if (ret != HISI_OK) {
        printf("register wifi event callback failed\r\n");
    }

    // 获取网卡接口（用于IP配置）
    g_lwip_netif = netifapi_netif_find(ifname);
    if (g_lwip_netif == NULL) {
        printf("%s: get netif failed\r\n", __FUNCTION__);
        return -1;
    }

    // 扫描周边WiFi热点
    ret = hi_wifi_sta_scan();
    if (ret != HISI_OK) {
        printf("hi_wifi_sta_scan failed, ret=%d\r\n", ret);
        return -1;
    }

    sleep(5);  // 休眠5秒，等待扫描结果

    // 打印扫描到的WiFi热点
    hi_wifi_ap_info *pst_results = malloc(sizeof(hi_wifi_ap_info) * WIFI_SCAN_AP_LIMIT);
    if (pst_results == NULL) {
        return -1;
    }
    ret = hi_wifi_sta_scan_results(pst_results, &num);
    if (ret == HISI_OK) {
        printf("Scanned WiFi APs:\r\n");
        for (unsigned int loop = 0; (loop < num) && (loop < WIFI_SCAN_AP_LIMIT); loop++) {
            printf("  SSID: %s\r\n", pst_results[loop].ssid);
        }
    }
    free(pst_results);

    // 连接指定WiFi热点
    ret = hi_wifi_start_connect();
    if (ret != 0) {
        return -1;
    }

    return 0;
}

// WiFi+MQTT任务（运行在独立线程）
void wifi_sta_task(void *arg)
{
    arg = arg;

    // 初始化并连接WiFi
    hi_wifi_start_sta();

    // 等待WiFi连接成功
    while (wifi_ok_flg == 0) {
        usleep(30000);  // 30毫秒休眠，避免占用过多CPU
    }

    usleep(2000000);  // WiFi连接成功后，休眠2秒再启动MQTT（确保网络稳定）

    // 启动MQTT测试（连接服务器+发布/订阅消息）
    mqtt_test();
}

// 程序入口（鸿蒙系统启动时执行）
void wifi_sta_entry(void)
{
    osThreadAttr_t attr;

    // 配置线程属性
    attr.name = "wifi_sta_demo";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 4096;  // 线程栈大小4KB
    attr.priority = 26;      // 线程优先级（26为中等优先级）

    // 创建并启动线程
    if (osThreadNew((osThreadFunc_t)wifi_sta_task, NULL, &attr) == NULL) {
        printf("[wifi_sta_demo] Failed to create wifi_sta_demo thread!\r\n");
    }
}

// 注册鸿蒙系统启动入口
SYS_RUN(wifi_sta_entry);